package com.ys.controller.api.account;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.config.MenuId;
import com.ys.entity.account.TbAdvanceType;
import com.ys.entity.account.TcwAdvanceAccount;
import com.ys.entity.sys.YsCol;
import com.ys.service.account.TcwAdvanceAccountService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 预支账户管理
 */
@Controller
@RequestMapping("/api/inter/tcwAdvanceAccount")
public class ApiInterTcwAdvanceAccountController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwAdvanceAccountController.class);

    @Autowired
    private CommonApiService<TcwAdvanceAccount> commonApiService;

    @Autowired
    private TcwAdvanceAccountService tcwAdvanceAccountService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwAdvanceAccount setSeachSql(TcwAdvanceAccount cond){

        cond.addLeftJoin("TS_UserBankInfo U ON A.UserBankInfoId = U.Id AND A.AccountType=0")
            .addLeftJoin("TCW_PartnerBankInfo P ON A.PartnerBankInfoId = P.Id AND A.AccountType=1")
                .addField("CASE WHEN A.AccountType=0 THEN U.Vyhzhmc ELSE P.Vyhzhmc END _ys_vyhzhmc")//银行账户名称
                .addField("CASE WHEN A.AccountType=0 THEN U.Vkhh ELSE P.Vkhh END _ys_vkhh")//开户行
                .addField("CASE WHEN A.AccountType=0 THEN U.Vyhzh ELSE P.Vyhzh END _ys_vyhzh");//银行账户编码
                //.addField("U.Vyhzhmc AS _ys_vyhzhmc")//银行账户名称
                //.addField("U.Vkhh AS _ys_vkhh")//开户行
                //.addField("U.Vyhzh AS _ys_vyhzh");//银行账户编码

        cond.addLeftJoin("TS_UserInfo B on  B.UserId = A.UserId")
                .addField("B.roleName AS roleName")//负责人岗位
                .addField("(B.UserId + '/' + B.UserName) AS _ys_nameLinked");//账户管理负责人

        cond.addLeftJoin("TS_OrganizationInfo O on  O.Orgid = A.Orgid")
                .addField("O.OrgName AS orgName");//账户管理部门

        //明细1
        cond.addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByRecharge FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX000' GROUP BY Pid) D1 on D1.Pid = A.Id AND 1=1")
                .addField("ISNULL(D1.totalPriceByRecharge, 0) AS totalPriceByRecharge");//“账户充值余额”，=充值类型之和（充值-归还）
        //明细2
        cond.addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByOther FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode NOT IN ('YZZHLX000','YZZHLX001') GROUP BY Pid) D2 on D2.Pid = A.Id AND 1=1")
                .addField("ISNULL(D2.totalPriceByOther, 0) AS totalPriceByOther");//台账明细金额”，=类型不为充值、报销的之和
        //明细3
        cond.addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceBySubmit FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX001' GROUP BY Pid) D3 on D3.Pid = A.Id AND 1=1")
                .addField("ISNULL(D3.totalPriceBySubmit, 0) AS totalPriceBySubmit");//台账报销金额,字段“总额”之和（预支类型为报销）

        //排序
        cond.setOrderby("A.Code DESC");

        cond = commonApiService.dataAuth(MenuId.TCW_AdvanceAccount, cond);
        return  cond;
    }


    //处理返回的数据
    public List<Map<String, Object>> setList(List<Map<String, Object>> resDate){
        List<Map<String, Object>> tableDate = new ArrayList();
        if(resDate!=null && resDate.size()>0){
            //循环处理数据
            for(int i=0;i<resDate.size();i++) {
                BigDecimal totalPriceByRecharge = BigDecimal.ZERO;//账户充值余额
                BigDecimal totalPriceByOther = BigDecimal.ZERO;//台账明细金额
                BigDecimal totalPriceBySubmit = BigDecimal.ZERO;//台账报销金额
                Map<String, Object> resItem = resDate.get(i);
                if(resItem.get("totalPriceByRecharge")!=null)totalPriceByRecharge = new BigDecimal(resItem.get("totalPriceByRecharge").toString());//账户充值余额
                if(resItem.get("totalPriceByOther")!=null)totalPriceByOther = new BigDecimal(resItem.get("totalPriceByOther").toString());//台账明细金额
                if(resItem.get("totalPriceBySubmit")!=null)totalPriceBySubmit = new BigDecimal(resItem.get("totalPriceBySubmit").toString());//台账报销金额

                //计算：账户可用金额 = 充值+报销-明细
                BigDecimal canUseMoney = totalPriceByRecharge.add(totalPriceBySubmit).subtract(totalPriceByOther);
                resItem.put("canUseMoney",canUseMoney);
                tableDate.add(resItem);
            }
        }
        return tableDate;
    }

    /**
     * 查询
     */
    @RequiresPermissions("tcwAdvanceAccount:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwAdvanceAccount cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_nameLinked");//工号/姓名
            if (nameLinked != null){
                cond.where("B.UserId LIKE '%" + nameLinked + "%'" + " OR  B.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            //获取
            JSONArray tableVoJAData = setList.getData();

            //转换
            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
            List<Map<String, Object>> resListNew = new ArrayList();
            resList.forEach(item-> resListNew.add(item));
            //处理数据
            List<Map<String, Object>> resultList = setList(resListNew);
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
            setList.setData(jsonArray);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwAdvanceAccount cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_AdvanceAccount)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TbAdvanceType> util = new ExportExcelUtils<>(new TbAdvanceType());
            String toFilePath = util.exportExcel(listData, listField, "预支账户管理");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwAdvanceAccountService.add(params,MenuId.TCW_AdvanceAccount);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcwAdvanceAccountService.update(params,MenuId.TCW_AdvanceAccount);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 保存子表信息
     */
    @RequestMapping("/toSaveItem")
    @ResponseBody
    public R toSaveItem(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwAdvanceAccountService.toSaveItem(params);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 弹出框
     */
    @RequestMapping("/searchForModal")
    @ResponseBody
    public LayuiTableVoJA searchForModal(@ModelAttribute TcwAdvanceAccount cond){
        cond = setSeachSql(cond);
        cond.setStatus(1);
        //岗位工种(0总经理 1副总经理 2责任月薪型员工 3绩效提奖型员工 4研发人员)
        cond.addField("CASE " +
                "WHEN A.AccountType = 0 THEN '员工账户' " +
                "WHEN A.AccountType = 1 THEN '合作商账户' " +
                " ELSE '' END accountTypeTxt");

        //关联运营公司
        cond.addLeftJoin("TS_OrganizationAccount OA ON OA.Orgid = A.Orgid AND OA.Status=1")
                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = OA.Vgsbm AND 1=1")
                .addField("OCA.Vgsbm AS vgsbm")
                .addField("OCA.Vgsjc AS vgsjc");

        LayuiTableVoJA setList = commonApiService.searchLay(cond);
        //获取
        JSONArray tableVoJAData = setList.getData();

        //转换
        List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
        List<Map<String, Object>> resListNew = new ArrayList();
        resList.forEach(item-> resListNew.add(item));
        //处理数据
        List<Map<String, Object>> resultList = setList(resListNew);
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
        setList.setData(jsonArray);
        return setList;
    }



}